package com.ygjy.webapplication;


import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.tencent.smtt.export.external.interfaces.JsPromptResult;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.net.URISyntaxException;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    X5WebView mWebView;
    SwipeRefreshLayout mSwipeRefreshLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        mWebView = findViewById(R.id.web);
        mSwipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        WindowInsetsControllerCompat controller = WindowCompat. getInsetsController(getWindow(),findViewById(R.id.main));
        controller.setAppearanceLightStatusBars(false);

        MainDialog mainDialog = new MainDialog();
        mainDialog.show(getSupportFragmentManager(),"mainDialog");



        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mWebView.reload();

            }
        });

        mWebView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                mSwipeRefreshLayout.setEnabled(scrollY == 0);
            }
        });

        mWebView.setWebViewClient(new WebViewClient(){

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
                mainDialog.dismiss();
                mSwipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onLoadResource(WebView webView, String s) {
                super.onLoadResource(webView, s);
                Log.d(TAG, "onLoadResource: "+s);
            }

            /*@Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                Log.d(TAG, "shouldOverrideUrlLoading: "+s);
                return super.shouldOverrideUrlLoading(webView, s);
            }*/

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
                Log.d(TAG, "shouldOverrideUrlLoading:1 '"+webResourceRequest.getUrl());
                return super.shouldOverrideUrlLoading(webView, webResourceRequest);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d(TAG, "shouldOverrideUrlLoading:2 "+url);
                Log.d(TAG, "should: "+ url.contains("https://t.me/")+" "+url.contains("api.whatsapp.com"));
                try {
                    //处理intent协议
                    if (url.startsWith("intent://")) {
                        Intent intent;
                        try {
                            intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                            intent.addCategory("android.intent.category.BROWSABLE");
                            intent.setComponent(null);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                                intent.setSelector(null);
                            }
                            List<ResolveInfo> resolves = getPackageManager().queryIntentActivities(intent,0);
                            if(resolves.size()>0){
                                startActivity(intent);
                            }
                            return true;
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        }
                    }

                    // 处理自定义scheme协议
                    if (!url.contains(BuildConfig.host)) {
                        Log.e("yxx","处理自定义scheme-->" + url);
                        try {
                            // 以下固定写法
                            final Intent intent = new Intent(Intent.ACTION_VIEW,
                                    Uri.parse(url));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                    | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                            startActivity(intent);
                        } catch (Exception e) {
                            // 防止没有安装的情况
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),"您所打开的第三方App未安装！",Toast.LENGTH_SHORT).show();
                        }
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

        });
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView webView, String s) {
                super.onReceivedTitle(webView, s);
                Log.d(TAG, "onReceivedTitle: "+s);
            }

            @Override
            public boolean onJsAlert(WebView webView, String s, String msg, JsResult jsResult) {
                Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
                return true;
            }

            @Override
            public boolean onJsBeforeUnload(WebView webView, String s, String s1, JsResult jsResult) {
                Log.d(TAG, "onJsBeforeUnload: ");
                return super.onJsBeforeUnload(webView, s, s1, jsResult);
            }

            @Override
            public boolean onJsConfirm(WebView webView, String s, String s1, JsResult jsResult) {
                Log.d(TAG, "onJsConfirm: ");
                return super.onJsConfirm(webView, s, s1, jsResult);
            }

            @Override
            public boolean onJsPrompt(WebView webView, String s, String s1, String s2, JsPromptResult jsPromptResult) {
                Log.d(TAG, "onJsPrompt: ");
                return super.onJsPrompt(webView, s, s1, s2, jsPromptResult);
            }
        });

        WebSettings webSetting = mWebView.getSettings();
        webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);//根据cache-control决定是否从网络上取数据。
        if (BuildConfig.DEBUG) {
//            webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存，只从网络获取数据.
        }
        webSetting.setAllowUniversalAccessFromFileURLs(false);
        webSetting.setAllowFileAccessFromFileURLs(false);
//        webSetting.setAllowFileAccess(false);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        webSetting.setDefaultTextEncodingName("UTF-8");
        webSetting.setSupportZoom(false);
        webSetting.setDisplayZoomControls(false);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);

        webSetting.setAppCacheMaxSize(30 * 1024 * 1024);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSetting.setMixedContentMode(2);
        }
        webSetting.setAppCachePath(getFilesDir().getAbsolutePath() + "cache/");
        webSetting.setDatabasePath(getFilesDir().getAbsolutePath() + "cache/");
        webSetting.setGeolocationDatabasePath(getFilesDir().getAbsolutePath() + "cache/");
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
//         webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
//         webSetting.setPreFectch(true);


        webSetting.setAllowContentAccess(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);

        
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
        mWebView.loadUrl(BuildConfig.host+"/#/pages/home/home");
    }

    private static final String TAG = "MainActivity";
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView.canGoBack()){
                mWebView.goBack();
            }else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}